<?php

namespace app\admin\controller;


use PhpOffice\PhpSpreadsheet\Spreadsheet;
use think\Db;
use think\Validate;

class Classroom  extends Base
{
    public function index(){
        extract(input());
        $where = [];
        if (isset($class_name) && !empty($class_name)) {
            $where['c.class_name'] = ['like', '%'.$class_name.'%'];
        }
        if (isset($school_id) && !empty($school_id)) {
            $where['s.id'] = $school_id;
            // 如果 school_id 不为空，说明本次搜索选择了学校。
            // 既然知道了学校，就可以将该学校下的专业查询出来，循环输出在搜索下拉框中，如此，就可以在搜索完成时选中选择的专业了。
            $class = Db::name('tp_major')->where('school_id', $school_id)->select();
        } else {
            // 本次没有选择学校进行搜索，用一个空数组代替。
            $class = [];
        }
        if (isset($major_id) && !empty($major_id)) {
            $where['m.id'] = $major_id;
        }
        $list = Db::name('tp_class')
            ->alias('c')
            // 关联专业表
            ->join('tp_major m', 'c.major_id=m.id')
            // 关联学校表
            ->join('tp_school s', 'm.school_id=s.id')
            ->field('c.id,class_name,m.major_name,s.school_name')
            ->where($where)
            ->paginate(5, false, ['query' => input()]);

        $page = $list->render();

        // 查询学校 - 搜索的下拉框使用
        $school = Db::name('tp_school')->select();

        return $this->fetch('classroom', [
            'data' => $list,
            'page' => $page,
            'school' => $school,
            'classroom' => $class
        ]);
    }
    public function add(){
       $data = Db::name('tp_school')->select();
        $this->assign('data',$data);
        return $this->fetch();
    }
    public function Getmajor(){
        $schoolId = input('school_id');
        $major = Db::name('tp_major')
            ->where('school_id',$schoolId)
            ->select();
       $options = ["<option value=''>请选择专业</option>"];
        foreach ($major as $v){
            $options[] = "<option value='".$v['id']."'>".$v['major_name']."</option>";
        }
        return $options;
    }
    public function addPost(){
        $data = input();
        $res = Db::name('tp_class')->insert($data);
        if($res){
            $this->success('添加成功');
        }else{
            $this->error('添加失败');
        }
    }
    public function edit(){
       $id = input('id');
       //查询所有数据
       $class = Db::name('tp_class')->find($id);
       //查询学校
        $school = Db::name('tp_school')->select();
        //查询这个班级在那个学校（id）
        $schoolId = Db::name('tp_major')->where('id',$class['major_id'])->value('school_id ');
        //查询当前这个班级所在学校下的专业
        $major = Db::name('tp_major')->where('school_id',$schoolId)->select();
        return $this->fetch('',[
            'classroom'=>$class,
            'school'=>$school,
            'school_id'=>$schoolId,
            'major'=>$major
        ]);
    }
    public function Edit_major(){
        $schoolId = input('school_id');
        $major = Db::name('tp_school')
            ->where('id',$schoolId)
            ->select();
        $options = ["<option value=''>请选择专业</option>"];
        foreach ($major as $v){
            $options[] = "<option value='".$v['id']."'>".$v['school_name']."</option>";
        }
        return $options;
    }
    public function editPost(){
        $data = input();
        $rule = [
            'class_name'  => 'require',
        ];
        $msg = [
            'class_name.require' => '班级名称不能为空',
        ];
        $validate = new Validate($rule, $msg);
        $result   = $validate->check($data);
        if (true!==$result){
            $this->error($validate->getError());
        }
        $edit = Db::name('tp_class')
            ->where('id',$data['id'])->update($data);
        if($edit){
            $this->success('修改成功','school/school');
        }else{
            $this->error('修改失败');
        }
    }
    public function del(){
        $data = input('id');
        $del = Db::name('tp_class')->delete($data);
        if($del==1){
            $this->success('删除成功','classroom/index');
        }else{
            $this->error('删除失败');
        }
    }
    public function batchDelete(){
        $ids = input('ids/a');
        //print_r($ids);die;
        $del = Db::name('tp_class')->delete($ids);
        if($del){
            $this->success('删除成功','classroom/index');
        }else{
            $this->error('删除失败');
        }
    }
    public function exportExcel()
    {
        // 查询要导出的数据
        $data = Db::name('tp_class')
            ->join('tp_major','tp_class.major_id=tp_major.id')
            ->join('tp_school','tp_major.school_id=tp_school.id')
            ->select();

        // 实例化
        $spreadsheet = new Spreadsheet();
        // 获取活动工作薄
        $sheet = $spreadsheet->getActiveSheet();

        // 获取单元格
        $cellA = $sheet->getCell('A1');
        // 设置单元格的值
        $cellA->setValue('ID');
        // 设置 A 列 列宽
        $sheet->getColumnDimension('A')->setWidth(10);
        // 设置第一行 行高
        $sheet->getRowDimension(1)->setRowHeight(20);

        $cellB = $sheet->getCell('B1');
        $cellB->setValue('班级名称');
        $sheet->getColumnDimension('B')->setWidth(20);

        $cellC = $sheet->getCell('C1');
        $cellC->setValue('专业名称');
        $sheet->getColumnDimension('C')->setWidth(30);

        $cellD = $sheet->getCell('D1');
        $cellD->setValue('所在学校');
        $sheet->getColumnDimension('D')->setWidth(40);

        // 设置样式 标题栏
        $styleArray = [
            'alignment' => [
                'horizontal' => 'center', //水平居中
                'vertical' => 'center', //垂直居中
            ],
            'font' => [
                'name' => '黑体',
                'bold' => false,
                'size' => 10
            ]
        ];
        // 设置样式 正文
        $styleArrayBody = [
            'alignment' => [
                'horizontal' => 'center', //水平居中
                'vertical' => 'center', //垂直居中
            ],
            'font' => [
                'name' => '宋体',
                'bold' => false,
                'size' => 10
            ]
        ];
        // 应用样式
        $sheet->getStyle('A1')->applyFromArray($styleArray);
        $sheet->getStyle('B1')->applyFromArray($styleArray);
        $sheet->getStyle('C1')->applyFromArray($styleArray);
        $sheet->getStyle('D1')->applyFromArray($styleArray);


        // 从 A2 开始填充数据
        foreach ($data as $k => $v) {
            $n = $k + 2;
            // 获取单元格
            $cellA = $sheet->getCell('A'.$n);
            // 设置单元格的值
            $cellA->setValue($v['id']);

            $cellB = $sheet->getCell('B'.$n);
            $cellB->setValue($v['class_name']);

            $cellC = $sheet->getCell('C'.$n);
            $cellC->setValue($v['major_name']);

            $cellD = $sheet->getCell('D'.$n);
            $cellD->setValue($v['school_name']);


            // 再给表格体设置样式
            $sheet->getStyle('A'.$n)->applyFromArray($styleArrayBody);
            $sheet->getStyle('B'.$n)->applyFromArray($styleArrayBody);
            $sheet->getStyle('C'.$n)->applyFromArray($styleArrayBody);
            $sheet->getStyle('D'.$n)->applyFromArray($styleArrayBody);

        }

        // 下载文件名
        $filename = '班级列表.xlsx';
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename='.$filename);
        header('Cache-Control: max-age=0');

        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save('php://output');
    }
    //导入
    public function Excel_export()
    {
        // 接收文件
        $file = $_FILES['file']['tmp_name'];
        // 创建读操作
        $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader('Xlsx');
        // 打开文件、载入excel表格
        $spreadsheet = $reader->load($file);
        // 获取活动工作薄
        $sheet = $spreadsheet->getActiveSheet();


        // 获取总行数
        $highestRow = $sheet->getHighestRow();

        // 存放插入成功的记录
        $successLog = [];
        // 存放插入失败的记录
        $failLog = [];

        // 从第二行开始读取表格数据，循环写入数据库
        for ($i = 2; $i <= $highestRow; $i++) {
            // 第 1 次循环获取第 2列 第 2 行单元格的值，第 2 次循环获取第 3 列 第 3 行单元格的值
            $class_name = $sheet->getCellByColumnAndRow(2, $i)->getValue();
            $major_id = $sheet->getCellByColumnAndRow(3, $i)->getValue();
            // 假设数据表有以下字段

            $data = [
                'class_name' => $class_name,
                'major_id' => $major_id,
            ];
            $insert = Db::name('tp_class')->insert($data);
            if ($insert) {
                $successLog[] = '第' . $i . '条，插入成功';
            } else {
                $failLog[] = '第' . $i . '条，插入失败';
            }
        }
        // 将成功数和失败数返回给 ajax
        return json(['success' => count($successLog), 'fail' => count($failLog)]);
    }
}